package com.asia5b.a5mall.middleware.base

import androidx.lifecycle.MutableLiveData
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * Created by zhangyuncai on 2020/8/19.
 */
class SimpleTransformer<T>(val simpleNetParams: SimpleNetParams) : ObservableTransformer<T, T> {
    override fun apply(upstream: Observable<T>): ObservableSource<T> {
        return upstream //io线程订阅
                .subscribeOn(Schedulers.io()) //遇到错误时重试,参数为重试几次
                .unsubscribeOn(Schedulers.io()) // 切换UI线程
                .observeOn(AndroidSchedulers.mainThread()) //.compose(ErrorTransformer<T>getInstance());
                .doOnSubscribe { disposable: Disposable? ->
                    if (simpleNetParams.isShowLoading) {
                        simpleNetParams.loadingLiveData.value=0
                    }
                }
                .doAfterTerminate {
                    if (simpleNetParams.isDissmissLoading) {
                        simpleNetParams.loadingLiveData.value=1
                    }
                }
    }
}

class SimpleNetParams constructor(var isShowLoading: Boolean = true,
                                  var isDissmissLoading: Boolean = true,
                                  var isToastError: Boolean = true,
                                  var requestTag: String? = null) {
    //请求接口增加一个标记符
    lateinit var loadingLiveData: MutableLiveData<Int>
}